package com.bnlr.lrparking.appui.publish;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.bnlr.lrparking.appui.stall.StallBegRentBuy;
import com.bnlr.lrparking.appui.stall.StallDealDetailActivity;
import com.bnlr.lrparking.constant.LrConstant;
import com.bnlr.lrparking.constant.Urls;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.bnlr.lrparking.app.Application;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.adapter.MyPublishAdapter;
import com.bnlr.lrparking.base.BaseActivity;
import com.bnlr.lrparking.app.AppConfig;
import com.bnlr.lrparking.model.BaseArrayBean;
import com.bnlr.lrparking.model.MyPublishBean;
import com.bnlr.lrparking.view.CarCommon;
import com.bnlr.lrparking.widget.refresh.RefreshHolderUtil;
import com.bnlr.lrparking.widget.refresh.XRefreshLayout;
import com.bnlr.nohttp.CallServer;
import com.bnlr.nohttp.CustomHttpListener;
import com.yolanda.nohttp.NoHttp;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 我的发布
 * @author tian
 */
public class MyPublishActivity extends BaseActivity {
    private Unbinder unbinder;
    @BindView(R.id.tv_nav_title)
    TextView tvTitle;
    @BindView(R.id.tv_nav_right)
    TextView tvRight;
    @BindView(R.id.swipe_my_publish)
    XRefreshLayout swipeRefreshLayout;
    @BindView(R.id.xv_my_publish)
    RecyclerView mRecyclerView;
    private MyPublishAdapter adapter;
    private List<MyPublishBean.DataBean> dataList = new ArrayList<>(); 
    private int currentPage = 1;
    /*@BindView(R.id.no_data)
    RelativeLayout empty;*/
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_publish);
        unbinder = ButterKnife.bind(this);
        tvTitle.setText("我的发布");
        tvRight.setText("发布信息");
        init();

    }

    @Override
    protected void onResume() {
        super.onResume();
        currentPage = 1;
        getMyPublishData(currentPage);
    }

    private void init() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        swipeRefreshLayout.setRefreshViewHolder(RefreshHolderUtil.getRefreshHolder(this));
        swipeRefreshLayout.setDelegate(new XRefreshLayout.BGARefreshLayoutDelegate() {
            @Override
            public void onBGARefreshLayoutBeginRefreshing(XRefreshLayout refreshLayout) {
                currentPage = 1;
                getMyPublishData(currentPage);
            }

            @Override
            public boolean onBGARefreshLayoutBeginLoadingMore(XRefreshLayout refreshLayout) {
                return false;
            }

        });
       // swipeRefreshLayout.beginRefreshing();

        adapter = new MyPublishAdapter(dataList);

        adapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                //  上拉加载
                currentPage++;
                getMyPublishData(currentPage);
            }
        },mRecyclerView);
        mRecyclerView.setAdapter(adapter);
       mRecyclerView.addOnItemTouchListener(new OnItemClickListener() {
           @Override
           public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
               MyPublishBean.DataBean md = dataList.get(position);
               if (md.getAuditStatus() == 0) {
                   if (LrConstant.BEG_RENT == md.getType() || LrConstant.BEG_SELL == md.getType()) {
                       Intent intent = new Intent(MyPublishActivity.this, StallBegRentBuy.class);
                       intent.putExtra("stall_id", md.getId());
                       startActivity(intent);
                   } else {
                       Intent intent = new Intent(MyPublishActivity.this, StallDealDetailActivity.class);
                       intent.putExtra("stall_id", md.getId());
                       startActivity(intent);
                   }
                   // 待审核
               } else if (md.getAuditStatus() == 2) {
                   if (LrConstant.BEG_RENT == md.getType() || LrConstant.BEG_SELL == md.getType()) {
                       Intent intent = new Intent(MyPublishActivity.this, StallBegRentBuy.class);
                       intent.putExtra("stall_id", md.getId());
                       intent.putExtra("is_waiting", true);
                       startActivity(intent);
                   } else {
                       Intent intent = new Intent(MyPublishActivity.this, StallDealDetailActivity.class);
                       intent.putExtra("stall_id", md.getId());
                       intent.putExtra("is_waiting", true);
                       startActivity(intent);
                   }
               } else if (md.getAuditStatus() == 3) {
                   if (LrConstant.RENT == md.getType() || LrConstant.SELL == md.getType()) {
                       Intent intent = new Intent(MyPublishActivity.this, PublishActivity.class);
                       intent.putExtra("alter_publish", md);
                       if (LrConstant.RENT == md.getType()) {
                           intent.putExtra("publish_tag", 1);
                       } else {
                           intent.putExtra("publish_tag", 2);
                       }
                       startActivity(intent);
                   } else {
                       Intent intent = new Intent(MyPublishActivity.this, PublishBegActivity.class);
                       intent.putExtra("alter_publish", md);
                       if (LrConstant.BEG_RENT == md.getType()) {
                           intent.putExtra("publish_tag", 3);
                       } else {
                           intent.putExtra("publish_tag", 4);
                       }
                       startActivity(intent);
                   }
               }
           }

           @Override
           public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
               MyPublishBean.DataBean item = dataList.get(position);
               startActivity(new Intent(MyPublishActivity.this,FailCauseActivity.class)
                       .putExtra("fail_cause",item.getRejectReason()));
           }
       });

        adapter.setOnItemDeleteListener(new MyPublishAdapter.OnItemDeleteListener() {
            @Override
            public void onDelete(View view, final int position, final MyPublishBean.DataBean item) {
                CarCommon carCommon = new CarCommon();
                carCommon.setClickSureListener(new CarCommon.ClickSureListener() {
                    @Override
                    public void setSure() {
                        deleteItem(item.getId(),position);
                    }
                });
                carCommon.CommonDialog(MyPublishActivity.this,"确定要删除该条信息吗",null);
            }
        });

        adapter.setOnItemOffListener(new MyPublishAdapter.OnItemOffListener(){
            @Override
            public void onOff(View view, final int position, final MyPublishBean.DataBean item) {
                CarCommon carCommon = new CarCommon();
               if (item.getAuditStatus() == 0) {
                   //   下线
                   carCommon.setClickSureListener(new CarCommon.ClickSureListener() {
                       @Override
                       public void setSure() {
                           sendOnOrOffStatus(item.getId(),position,1);
                       }
                   });
                   carCommon.CommonDialog(MyPublishActivity.this,"确定要下线该条信息吗",null);
               } else if (item.getAuditStatus() == 1) {
                   //   上线
                   carCommon.setClickSureListener(new CarCommon.ClickSureListener() {
                               @Override
                               public void setSure() {
                                   sendOnOrOffStatus(item.getId(),position,2);
                               }
                   });
                   carCommon.CommonDialog(MyPublishActivity.this,"确定要上线该条信息吗",null);
               }

            }
        });
    }
    private void sendOnOrOffStatus (int id, final int position, final int tag) {
        try {
            mRequest = NoHttp.createStringRequest(Urls.SPACE_IP, LrConstant.POST);
            mRequest.add("action", "SetParkSpaceStatus");
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("parkSpaceId",id);
            mRequest.add("phonePara", Application.DEVICE_ID);
            if (tag == 1) {
                mRequest.add("status",1);
            } else if (tag == 2) {
                mRequest.add("status",0);
            }

            // 添加到请求队列+
            CallServer.getRequestInstance().add(this, mRequest,
                    new CustomHttpListener<BaseArrayBean>(this, true, BaseArrayBean.class) {
                        @Override
                        public void doWork(BaseArrayBean data, String code) {
                            if (TextUtils.equals("1", code)) {
                                if (tag == 1) {
                                    dataList.get(position).setAuditStatus(1);
                                    ToastUtils.showShort("信息下线成功！");
                                } else if (tag == 2) {
                                    dataList.get(position).setAuditStatus(0);
                                    ToastUtils.showShort("信息上线成功！");
                                }

                                adapter.notifyItemChanged(position);
                            } else {
                                ToastUtils.showShort(data.getMsg()+"");
                            }
                        }
                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {

                        }
                    }, true);
        } catch (Exception e) {
        }
    }
    private void deleteItem(int id, final int position) {
        try {
            mRequest = NoHttp.createStringRequest(Urls.SPACE_IP, LrConstant.POST);
            mRequest.add("action", "SetParkSpaceStatus");
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("parkSpaceId",id);
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("status",4);

            // 添加到请求队列+
            CallServer.getRequestInstance().add(this, mRequest,
                    new CustomHttpListener<BaseArrayBean>(this, true, BaseArrayBean.class) {
                        @Override
                        public void doWork(BaseArrayBean data, String code) {
                            if (TextUtils.equals("1", code)) {
                                dataList.remove(position);
                                adapter.notifyDataSetChanged();
                                ToastUtils.showShort("删除成功！");
                                if (dataList.size() == 0) {
                                    //empty.setVisibility(View.VISIBLE);
                                    adapter.setEmptyView(R.layout.publish_empty_layout);
                                }
                            } else {
                                ToastUtils.showShort(data.getMsg()+"");
                            }
                        }
                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {

                        }
                    }, true);
        } catch (Exception e) {
        }
    }

    @OnClick({R.id.tv_nav_right})
    public void myPublishOnClick (View view) {
        switch (view.getId()) {
            case R.id.tv_nav_right:
                    startActivity(new Intent(this,GoPublishActivity.class));
                break;
            default:
                break;
        }
    }
    private void getMyPublishData(final int page) {
        try {
            mRequest = NoHttp.createStringRequest(Urls.SPACE_IP, LrConstant.POST);
            mRequest.add("action", "GetUserParkSpace");
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("userId",AppConfig.getInstance().getString("uid", ""));
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("pageIndex", page);
            mRequest.add("days", 30);
            mRequest.add("status",4);
            mRequest.add("isAll", 1);
            // 添加到请求队列+
            CallServer.getRequestInstance().add(this, mRequest,
                    new CustomHttpListener<MyPublishBean>(this, true, MyPublishBean.class) {
                        @Override
                        public void doWork(MyPublishBean data, String code) {
                            if (TextUtils.equals("1", code)) {
                                if (adapter != null) {
                                    if (data != null && data.getData().size() != 0) {
                                        //empty.setVisibility(View.GONE);
                                        if (page == 1) {
                                            dataList = data.getData();
                                            adapter.setNewData(data.getData());
                                        } else {
                                            dataList.addAll(data.getData());
                                            adapter.notifyDataSetChanged();
                                        }
                                        adapter.loadMoreComplete();
                                    } else {
                                        if (page == 1) {
                                            dataList.clear();
                                            adapter.notifyDataSetChanged();
                                            adapter.setEmptyView(R.layout.publish_empty_layout);
                                            //empty.setVisibility(View.VISIBLE);
                                        } else {
                                            adapter.loadMoreEnd();
                                        }
                                    }
                                }
                            } else {
                                ToastUtils.showShort(data.getMsg()+"");
                            }
                        }
                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                                if (swipeRefreshLayout != null) {
                                    swipeRefreshLayout.endRefreshing();
                                }
                        }
                    }, false);
        } catch (Exception e) {
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbinder.unbind();

    }
}
